<!--进货订单-->
<template>
    <el-form :model="purform" ref="purref" :inline="true" style="text-align: left;">
        <el-form-item label="进货单号:" prop="code">
            <el-input placeholder="请输入" v-model="purform.code"></el-input>
        </el-form-item>
        <el-form-item label="单据状态" prop="ordstatus">
            <el-select placeholder="请选择" style="width:200px" v-model="purform.ordstatus">
                <el-option v-for="item in status" :key="item.dict_value" :label="item.dict_label" :value="item.dict_value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="sup">
            <el-select placeholder="请选择" style="width:200px" v-model="purform.sup">
                <el-option v-for="item in suppliers" :key="item.sup_id" :label="item.sup_name" :value="item.sup_id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="进货日期" prop="date">
            <el-date-picker v-model="purform.date" :value-format="dateFormat" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" style="width: 350px;" />
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
            <el-button @click="AdvancedSearch">高级查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button type="success" @click="ShowAdd">添加</el-button>
        <el-button type="danger" @click="ShowDeleteAll">删除</el-button>
        <el-button @click="ShowAudit">审核</el-button>
        <el-button @click="ShowCancelAll">撤销</el-button>
        <el-button @click="Export">导出</el-button>
        <el-button @click="Refresh">刷新</el-button>
    </div>
    <!--表格-->
    <el-table :data="purdata"  stripe style="margin-top: 10px;" @selection-change="SelectChange">
        <el-table-column fixed  type="selection"></el-table-column>
        <el-table-column fixed  type="index" label="序号" width="100"></el-table-column>
        <el-table-column fixed  label="进货单号" width="200px">
            <template #default="scope">
                <span style="color: green;cursor: pointer;" @click="ShowInfo(scope.row)">{{ scope.row.pur_code }}</span>
            </template>
        </el-table-column>
        <el-table-column fixed prop="pur_status" label="单据状态"></el-table-column>
        <el-table-column fixed prop="pur_date" label="进货日期" width="200px"></el-table-column>
        <el-table-column prop="sup_name" label="供应商" width="200px"></el-table-column>
        <el-table-column prop="sup_linkman" label="联系人"></el-table-column>
        <el-table-column prop="sup_linkphone" label="联系方式" width="200px"></el-table-column>
        <el-table-column prop="pur_depName" label="进货部门" width="120px"></el-table-column>
        <el-table-column prop="pur_userName" label="进货人"></el-table-column>
        <el-table-column prop="pur_num" label="货品数量"></el-table-column>
        <el-table-column prop="pur_total" label="货品金额" width="120px"></el-table-column>
        <el-table-column label="进货货品" width="300px">
            <template #default="scope">
                <el-tooltip
                    effect="dark"
                    :content="scope.row.proc_list_full"
                    placement="top"
                    :disabled="!scope.row.proc_list_full || scope.row.proc_list_full.split('、').length <= 3"
                >
                    <span>{{ scope.row.proc_list }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="create_name" label="制单人"></el-table-column>
        <el-table-column prop="create_time" label="制单时间" width="200px"></el-table-column>
        <el-table-column prop="approver_name" label="审核人"></el-table-column>
        <el-table-column prop="approver_time" label="审核时间" width="200px"></el-table-column>
        <el-table-column label="操作" fixed="right" width="160px">
            <template #default="scope">
                <el-button 
                    v-if="['草稿', '待审核'].includes(scope.row.pur_status)"
                    type="success" 
                    text="编辑" @click="ShowUpdate(scope.row)">
                    编辑
                </el-button>
                <el-button 
                    v-if="['草稿', '待审核'].includes(scope.row.pur_status)"
                    type="danger" 
                    text="删除" @click="ShowDelete(scope.row.pur_id)">
                    删除
                </el-button>
                <el-button 
                    v-if="['未入库', '驳回'].includes(scope.row.pur_status)"
                    type="danger" 
                    text="撤销" @click="ShowCancel(scope.row.pur_id)">
                    撤销
                </el-button>
            </template>
        </el-table-column>
    </el-table>

     <!-- 页码 -->
    <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>


    <!--高级查询-->
    <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: left;">高级查询</h4>
        </template>
        <template #default>
            <el-form label-width="120px" label-position="top" :model="searchform" ref="searchref">
                <el-row :gutter="24">
                    <!-- 左列 -->
                    <el-col :span="12">
                        <el-form-item label="进货单号" prop=code>
                            <el-input placeholder="请输入" v-model="searchform.code"/>
                        </el-form-item>
                        <el-form-item label="进货金额" prop="total">
                            <div style="display: flex; align-items: center;">
                                <el-input placeholder="请输入" v-model="searchform.starttotal" />
                                <span style="margin: 0 8px;">~</span>
                                <el-input placeholder="请输入" v-model="searchform.endtotal"/>
                            </div>
                        </el-form-item>
                        <el-form-item label="进货日期" prop="date">
                            <el-date-picker v-model="searchform.date" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
                        </el-form-item>
                        <el-form-item label="进货数量"  prop="num">
                            <div style="display: flex; align-items: center;">
                                <el-input placeholder="请输入" v-model="searchform.startnum"/>
                                <span style="margin: 0 8px;">~</span>
                                <el-input placeholder="请输入" v-model="searchform.endnum"/>
                            </div>
                        </el-form-item>
                        <el-form-item label="单据状态" prop="status">
                            <el-select placeholder="请选择" v-model="searchform.status">
                                <el-option v-for="item in status" :key="item.dict_value" :label="item.dict_label" :value="item.dict_value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="供应商" prop="sup">
                            <el-select placeholder="请选择" v-model="searchform.sup">
                                <el-option v-for="item in suppliers" :key="item.sup_id" :label="item.sup_name" :value="item.sup_id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="联系人" prop="suplink">
                            <el-input placeholder="请输入" v-model="searchform.suplink"/>
                        </el-form-item>
                    </el-col>
                    <!-- 右列 -->
                    <el-col :span="12">
                        <el-form-item label="进货部门" prop="dep">
                            <el-select placeholder="请选择" v-model="searchform.dep">
                                <el-option v-for="item in deps" :key="item.department_id" :label="item.department_name" :value="item.department_id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="进货人" prop="user">
                            <el-select placeholder="请选择" v-model="searchform.user">
                                <el-option v-for="item in users" :key="item.user_id" :label="item.user_name" :value="item.user_id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="制单人" prop="createname">
                            <el-input placeholder="请输入" v-model="searchform.createname"/>
                        </el-form-item>
                        <el-form-item label="制单时间" prop="createtime">
                            <el-date-picker v-model="searchform.createtime" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
                        </el-form-item>
                        <el-form-item label="审核人" prop="approvername">
                            <el-input placeholder="请输入" v-model="searchform.approvername"/>
                        </el-form-item>
                        <el-form-item label="审核时间" prop="approvertime">
                            <el-date-picker v-model="searchform.approvertime" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="AdvancedReset">重置</el-button>
                <el-button @click="drawer = false">关闭</el-button>
                <el-button type="primary" @click="AdvancedOk">确定</el-button>
            </div>
        </template>
    </el-drawer>

     <!--删除模态框-->
     <el-dialog v-model="DeleteialogVisible" width="400" style="text-align: left;"  align-center>
        <span>确定删除吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Delete()">确定</el-button>
            </div>
        </template>
    </el-dialog>

     <!--选中删除模态框-->
     <el-dialog v-model="DeleteialogVisible2" width="400" style="text-align: left;"  align-center>
        <span>确定删除选中的数据吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible2 = false">取消</el-button>
                <el-button type="primary" @click="DeleteAll()">确定</el-button>
            </div>
        </template>
    </el-dialog>


    <!--撤销模态框-->
    <el-dialog v-model="CancelDialogVisible" width="400" style="text-align: left;"  align-center>
        <span>确定撤销吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="CancelDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Cancel()">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--选中撤销模态框-->
    <el-dialog v-model="CancelDialogVisible2" width="400" style="text-align: left;"  align-center>
        <span>确定撤销选中的数据吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="CancelDialogVisible2 = false">取消</el-button>
                <el-button type="primary" @click="CancelAll()">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--审核模态框-->
    <el-dialog v-model="AuditDialogVisible" title="审核" width="400" style="text-align: left;" align-center>
        <div>
            <div style="margin-bottom: 15px;">
                <div>审核结果</div>
                <div style="margin-top: 10px;">
                    <el-radio v-model="auditResult" label="通过" style="margin-right: 20px;" value="4">通过</el-radio>
                    <el-radio v-model="auditResult" label="驳回" value="3">驳回</el-radio>
                </div>
            </div>
            <div>
                <div>审核意见</div>
                <el-input 
                    v-model="auditComment" 
                    type="textarea" 
                    rows="5" 
                    placeholder="请输入"
                    style="margin-top: 10px;"
                ></el-input>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="AuditDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Audit()">确定</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script>
import {ref,reactive,onMounted, computed} from 'vue';
import http from '../auth/index';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';//路由
import * as XLSX from 'xlsx';
export default {
setup()
    {
        const router = useRouter();//路由
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));
        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        // 货品列表格式化函数
        function formatProductList(products) {
            if (!products) return "";
            
            // 如果是字符串先转为数组（如"三锅头、可笑、何必"）
            const productArray = Array.isArray(products) 
                ? products 
                : products.split('、').filter(Boolean);
            
            if (productArray.length <= 3) {
                return productArray.join('、');
            } else {
                const firstThree = productArray.slice(0, 3).join('、');
                return `${firstThree}等${productArray.length}项....`;
            }
        }

        //查询所有单据状态
        const status=ref([]);
        function GetStatus(){
            return http.get("/DictData/GetAllDictDataBytype?typeid=6")
            .then(res=>{
                status.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有供应商
        const suppliers=ref([]);
        function GetSuppliers(){
            return http.get("/Supplier/GetAllSupplier")
            .then(res=>{
                suppliers.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有部门
        const deps=ref([]);
        function GetDepartments(){
            return http.get("/Department/GetDepartments")
            .then(res=>{
                deps.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有用户
        const users=ref([]);
        function GetUsers(){
            return http.get("/User/GetAllUser")
            .then(res=>{
                users.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }

        //导出
        function Export(){
            if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要导出的数据.',
                    type: 'warning',
                })
                return;
            }
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 准备数据
            const excelData = selectdata.value.map((row) => ({
                '序号': row.pur_id,
                '进货单号': row.pur_code,
                '单据状态': row.pur_status,
                '进货日期': row.pur_date,
                '供应商': row.sup_name,
                '联系人': row.sup_linkman,
                '联系方式': row.sup_linkphone,
                '进货部门': row.pur_depName,
                '进货人': row.pur_userName,
                '货品数量': row.pur_num,
                '货品金额': row.pur_total,
                '进货货品': row.proc_list,
                '制单人': row.create_name,
                '制单时间': row.create_time,
                '审核人': row.approver_name,
                '审核时间': row.approver_time
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "进货单");
            // 导出并下载
            XLSX.writeFile(wb, `进货单${new Date().toLocaleDateString()}.xlsx`);
        }

        //当前进货单id
        const purid=ref("");


        //刷新
        function Refresh(){
           All();
        }
        

        //#region 查询
        
        const purref=ref("");
        const purform=reactive({
            code:"",
            ordstatus:"",
            sup:"",
            date:[null,null]
        })

        function Reset(){
            purref.value?.resetFields();
            All();
        }

        //表格数据
        const purdata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);
        //日期格式
        const dateFormat = 'YYYY-MM-DD HH:mm:ss';

        // 状态映射计算属性
        const statusMap = computed(() => {
            const map = {};
            if (status.value && status.value.length > 0) {
                status.value.forEach(item => {
                    map[item.dict_value] = item.dict_label;
                });
            }
            return map;
        });

        //查询
        function Search() {
            All();
        }

        //查询数据
        function All(){
        
            http.get("/Purchase_h/GetPurchase_h", {
                params: {
                    code: purform.code,
                    status: purform.ordstatus,
                    sup:purform.sup,
                    starttime:purform.date[0],
                    endtime:purform.date[1],
                    CurrentPage: currentPage.value
                }
            }).then(res => {
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换并排序
                const Data = res.data.list.map(item => ({
                    ...item, // 复制原始对象的所有属性
                    pur_date: formatDateTime(new Date(item.pur_date)),
                    create_time: formatDateTime(new Date(item.create_time)),
                    approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                    pur_total: item.pur_total ? Number(item.pur_total).toFixed(2) : "0.00",
                    proc_list_full: item.proc_list,
                    proc_list: formatProductList(item.proc_list),
                    pur_status: statusMap.value[item.pur_status] || "未知状态",
                }));

                // 按照创建时间降序排序
                Data.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));

                purdata.value = Data;
            }).catch(err => {
                console.log(err)
            })
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }


        //#endregion


        //#region 高级查询
        const drawer=ref(false);
        function AdvancedSearch(){
            drawer.value=true
        }
        const searchref=ref("");
        const searchform=reactive({
            code:"",
            total:"",
            starttotal:"",
            endtotal:"",
            date:[null,null],
            num:"",
            startnum:"",
            endnum:"",
            status:"",
            sup:"",
            suplink:"",
            dep:"",
            user:"",
            createname:"",
            createtime:[null,null],
            approvername:"",
            approvertime:[null,null]
        })

         //重置
         function AdvancedReset(){
            searchref.value?.resetFields();
            searchform.starttotal="",
            searchform.endtotal="",
            searchform.startnum="",
            searchform.endnum=""
        }


        function AdvancedOk(){
            http.get("/Purchase_h/GetAdvancedPurchase_h",{
                params:{
                    code:searchform.code,
                    starttotal:searchform.starttotal,
                    endtotal:searchform.endtotal,
                    startdate:searchform.date[0],
                    enddate:searchform.date[1],
                    startnum:searchform.startnum,
                    endnum:searchform.endnum,
                    status:searchform.status,
                    sup:searchform.sup,
                    suplink:searchform.suplink,
                    dep:searchform.dep,
                    user:searchform.user,
                    createname:searchform.createname,
                    startcreatetime:searchform.createtime[0],
                    endcreatetime:searchform.createtime[1],
                    approvername:searchform.approvername,
                    startapprovertime:searchform.approvertime[0],
                    endapprovertime:searchform.approvertime[1],
                    CurrentPage:currentPage.value
                }
            }).then(res => {
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换
                const Data = res.data.list.map(item => ({
                    ...item, // 复制原始对象的所有属性
                    pur_date: formatDateTime(new Date(item.pur_date)),
                    create_time: formatDateTime(new Date(item.create_time)),
                    approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                    pur_total: item.pur_total ? Number(item.pur_total).toFixed(2) : "0.00",
                    proc_list_full: item.proc_list,
                    proc_list: formatProductList(item.proc_list),
                    pur_status: statusMap.value[item.pur_status] || "未知状态",
                }));
                purdata.value = Data;
            }).catch(err => {
                console.log(err)
            })
        }

        //#endregion

        //#region 跳转到新增界面
        function ShowAdd(){
            router.push("purchaseadd");
        }
        //#endregion

        //#region 删除

            //删除模态框
            const DeleteialogVisible=ref(false);
            //删除模态框
            function ShowDelete(id){
                purid.value=id;
                DeleteialogVisible.value=true;
            }
            async function Delete(){
                try {
                    // 1. 根据 purid 获取进货明细
                    const detailRes = await http.get("/Purchase_d/GetPurchase_Ds?purid=" + purid.value);
                    const details = detailRes.data;

                    // 2. 遍历明细，将数量从库存中减去
                    for (const item of details) {
                        const productRes = await http.get(`/Product/GetProductById?id=${item.proc_id}`);
                        const product = productRes.data;
                        if (product) {
                            const newInventory = (product.proc_ky_inventory || 0) - (item.proc_pur_num || 0);
                            await http.put(`/Product/Updateky?id=${item.proc_id}&inventory=${newInventory}`);
                        }
                    }

                    // 3. 删除进货单
                    const deleteRes = await http.put("/Purchase_h/DeletePurchase_h?id=" + purid.value);
                    if (deleteRes.data > 0) {
                        ElMessage({
                            message: '删除成功，库存已更新.',
                            type: 'success',
                        });
                        All();
                        DeleteialogVisible.value = false;
                    } else {
                        ElMessage.error('删除失败.');
                    }
                } catch (err) {
                    console.error("删除失败:", err);
                    ElMessage.error('删除操作失败.');
                }
            }

            const DeleteialogVisible2=ref(false);
            function ShowDeleteAll(){
                if(selectdata.value.length==0){
                    ElMessage({
                        message: '请选择要删除的数据.',
                        type: 'warning',
                    })
                    return;
                }
                
                // 检查选中的单据是否都可删除
                const invalidItems = selectdata.value.filter(item => 
                    !['草稿', '待审核'].includes(item.pur_status)
                );

                if (invalidItems.length > 0) {
                    ElMessage({
                        message: '选中的单据中包含不可删除的状态(只有草稿或待审核状态可删除)',
                        type: 'warning',
                    });
                    return;
                }
                
                DeleteialogVisible2.value=true;
            }

            //批量删除
            async function DeleteAll(){
                try {
                    for (const row of selectdata.value) {
                        const detailRes = await http.get("/Purchase_d/GetPurchase_Ds?purid=" + row.pur_id);
                        const details = detailRes.data;

                        for (const item of details) {
                            const productRes = await http.get(`/Product/GetProductById?id=${item.proc_id}`);
                            const product = productRes.data;
                            if (product) {
                                const newInventory = (product.proc_ky_inventory || 0) - (item.proc_pur_num || 0);
                                await http.put(`/Product/Updateky?id=${item.proc_id}&inventory=${newInventory}`);
                            }
                        }
                        await http.put("/Purchase_h/DeletePurchase_h?id=" + row.pur_id);
                    }
                    ElMessage({
                        message: '选中单据删除成功，库存已更新.',
                        type: 'success',
                    });
                    All();
                    DeleteialogVisible2.value = false;
                } catch (err) {
                    console.error("批量删除失败:", err);
                    ElMessage.error('批量删除操作失败.');
                }
            }


        //#endregion

        //#region 跳转到修改页面
        function ShowUpdate(row){
            router.push({
                name:"purchaseupdate",
                params:{
                    purid:row.pur_id,
                    purcode:row.pur_code
                }
            })
        }
        
        //#endregion

        //#region 撤销
        //当单据状态为，未入库且驳回的状态时可以撤销（待审核）
        const CancelDialogVisible=ref(false);
        function ShowCancel(id){
            purid.value=id;
            CancelDialogVisible.value=true;
        }
        //撤销
        function Cancel(){
            http.put("/Purchase_h/UpdateStatus?purid="+purid.value+"&status=2")
            .then(res=>{
                if(res.data>0){
                    ElMessage({
                        message: '撤销成功.',
                        type: 'success',
                    })
                    All();
                    CancelDialogVisible.value=false;
                }else{
                    ElMessage.error('撤销失败.')
                }
            }).catch(err=>{
                console.log(err);
            })
        }
        
        //选中撤销
        const CancelDialogVisible2=ref(false);
        function ShowCancelAll() {
            if(selectdata.value.length === 0) {
                ElMessage({
                    message: '请选择要撤销的单据.',
                    type: 'warning',
                });
                return;
            }
            
            // 检查是否有可撤销的单据
            const validItems = selectdata.value.filter(item => 
                item.pur_status === "未入库" || item.pur_status === "驳回");
            
            if (validItems.length === 0) {
                ElMessage({
                    message: '选中的单据中没有可撤销的单据(只有未入库或驳回状态可撤销)',
                    type: 'warning',
                });
                return;
            }
            
            CancelDialogVisible2.value = true;
        }
        //批量撤销
        function CancelAll(){
            selectdata.value.forEach(item => {
                if(item.pur_status === "未入库" || item.pur_status === "驳回"){
                    http.put("/Purchase_h/UpdateStatus?purid="+item.pur_id+"&status=2")
                    .then(res=>{
                        if(res.data>0){
                            ElMessage({
                                message: '撤销成功.',
                                type: 'success',
                            })
                            All();
                            CancelDialogVisible2.value=false;
                        }else{
                            ElMessage.error('撤销失败.')
                        }
                    }).catch(err=>{
                        console.log(err);
                    })
                }
            })
        }
        //#endregion

        //#region 审核
        //审核模态框
        const AuditDialogVisible=ref(false);
        const auditResult=ref("3");
        const auditComment=ref("");
        function ShowAudit(){
            if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要审核的单据.',
                    type: 'warning',
                })
                return;
            }
            //检查是否有可审核的单据
            const validItems = selectdata.value.filter(item => 
                item.pur_status === "待审核");
            if(validItems.length==0){
                ElMessage({
                    message: '选中的单据中没有可审核的单据(只有待审核状态可审核)',
                    type: 'warning',
                })
                return;
            }
            AuditDialogVisible.value=true;
        }

        function Audit(){
            selectdata.value.forEach(item => {
                if(item.pur_status === "待审核"){
                    http.put("/Purchase_h/ApproverPurchase_h?purid="+item.pur_id+"&status="+auditResult.value+"&approvername="+user.name+"&approvertime="+formatDateTime(new Date()))
                    .then(res=>{
                        if(res.data>0){
                            ElMessage({
                                message: '审核成功.',
                                type: 'success',
                            })
                            All();
                            AuditDialogVisible.value=false;
                        }else{
                            ElMessage.error('审核失败.')
                        }
                    }).catch(err=>{
                        console.log(err);
                    })
                }
            })
        }
        //#endregion


        //#region 查看详情信息
        function ShowInfo(row){
            router.push({
                name:"purchaseinfo",
                params:{
                    purid:row.pur_id,
                    purcode:row.pur_code
                }
            })
        }

        //挂载
        onMounted(() => {
            // 先加载状态数据，然后再加载其他数据
            GetStatus().then(() => {
                // 状态数据加载完成后，再执行查询
                All();
            });
            // 同时加载其他数据
            GetSuppliers();
            GetDepartments();
            GetUsers();
        });

        return{
            AdvancedSearch,
            drawer,
            status,
            purref,
            purform,
            Reset,
            suppliers,
            purdata,
            rows,
            currentPage,
            dateFormat,
            handlePageChange,
            Search,
            searchform,
            searchref,
            AdvancedReset,
            AdvancedOk,
            deps,
            users,
            ShowAdd,
            selectdata,
            SelectChange,
            Export,
            DeleteialogVisible,
            ShowDelete,
            Delete,
            purid,
            DeleteAll,
            DeleteialogVisible2,
            ShowDeleteAll,
            ShowUpdate,
            ShowCancel,
            CancelDialogVisible,
            Cancel,
            CancelDialogVisible2,
            ShowCancelAll,
            CancelAll,
            AuditDialogVisible,
            auditResult,
            auditComment,
            ShowAudit,
            Audit,
            Refresh,
            ShowInfo
        }
    }
}
</script>

<style scoped>

</style>